import {
  getCorpList,
  getUserId,
  getInsLsPkg,
  getPlcyParam,
  getDetailInfor,
  getSave,
  getUpdateSave,
  getUpdateSaveStart,
  getSaveStart,
  getDetailInforAccu,
  getAccuLsPkg,
  getInsertStart,
  getInsert,
  getAccuDetail,
  getUpdate,
} from '@/services/waresave';
import moment from 'moment';
import { message } from 'antd';
import router from 'umi/router';
import _ from 'lodash';

export default {
  state: {
    userType: '',
    comList: [],
    respDataList: [],
    supplyList: [],
    insUnifyFlag: 3,
    unitId: undefined,
    unitName: undefined,
    insPkgListArr: [],
    respListArr: [],
    index: 0,
    supplyListFlag: true,
  },

  effects: {
    // 获取公司
    *fetchCorpList({ payload }, { call, put, select }) {
      const response = yield call(getCorpList, payload);
      const userType = yield select(state => state.waresave.userType);
      if (response.success) {
        if (Number(userType) === 1) {
          yield put({
            type: 'updateComList',
            payload: response.data,
          });
        } else {
          yield put({
            type: 'getCorpList',
            payload: response.data,
          });
        }
        return response.data;
      }
      return message.warning(response.message);
    },
    *fetchUserId({ payload }, { call, put }) {
      const response = yield call(getUserId, payload);
      if (response.success) {
        yield put({
          type: 'getUserId',
          payload: response.data,
        });
      } else {
        message.warning(response.message);
      }
    },
    *fetchInsLsPkg({ payload }, { call, put }) {
      const response = yield call(getInsLsPkg, payload);
      if (response.success) {
        yield put({
          type: 'getInsLsPkg',
          payload: response.data,
        });
      } else {
        message.warning(response.message);
      }
    },

    *fetchPlcyParam({ payload }, { call, put }) {
      const response = yield call(getPlcyParam, payload);
      if (response.success) {
        yield put({
          type: 'getPlcyParam',
          payload: response.data,
        });
      } else {
        message.warning(response.message);
      }
    },

    *fetchDetailInfor({ payload }, { call, put }) {
      const response = yield call(getDetailInfor, payload);
      const areaList = [];
      if (response.success) {
        areaList.push({
          areaId: response.data.areaId,
          areaName: response.data.areaName,
        });

        yield put({
          type: 'publicdata/getAreaList',
          payload: areaList,
        });

        const res = yield call(getInsLsPkg, { areaId: response.data.areaId });
        if (res.success) {
          yield put({
            type: 'getInsLsPkg',
            payload: res.data,
          });
          yield put({
            type: 'getDetailInfor',
            payload: response.data,
          });
        } else {
          message.warning(res.message);
        }
      } else {
        message.warning(response.message);
      }
    },
    *fetchSave({ payload }, { call, select }) {
      const insAccoId = yield select(state => state.waresave.insAccoId);
      const response = insAccoId
        ? yield call(getUpdateSave, { ...payload, insAccoId })
        : yield call(getSave, payload);
      if (response.success) {
        router.goBack();
      } else {
        message.warning(response.message);
      }
    },
    *fetchSaveStart({ payload }, { call, select }) {
      const insAccoId = yield select(state => state.waresave.insAccoId);
      const response = insAccoId
        ? yield call(getUpdateSaveStart, { ...payload, insAccoId })
        : yield call(getSaveStart, payload);
      if (response.success) {
        router.goBack();
      } else {
        message.warning(response.message);
      }
    },
    // 只改了dispatch的社保详情
    *fetchDetailInforPage({ payload }, { call }) {
      const response = yield call(getDetailInfor, payload);
      if (response.success) {
        return response;
      }
      return message.warning(response.message);
    },
    // 以下只改了dispatch公积金大库
    *fetchDetailInforAccuPage({ payload }, { call }) {
      const response = yield call(getDetailInforAccu, payload);
      if (response.success) {
        return response;
      }
      return message.warning(response.message);
    },
    *fetchAccuCorpList({ payload }, { call }) {
      const response = yield call(getCorpList, payload);
      if (response.success) {
        return response;
      }
      return message.warning(response.message);
    },
    *fetchAccuLsPkg({ payload }, { call }) {
      const response = yield call(getAccuLsPkg, payload);
      return response;
    },
    *fetchInsertStart({ payload }, { call }) {
      const response = yield call(getInsertStart, payload);
      return response;
    },
    *fetchInsert({ payload }, { call }) {
      const response = yield call(getInsert, payload);
      return response;
    },
    *fetchAccuDetail({ payload }, { call, put }) {
      const response = yield call(getAccuDetail, payload);
      const areaList = [];
      if (response.success) {
        areaList.push({
          areaId: response.data.areaId,
          areaName: response.data.areaName,
        });

        yield put({
          type: 'publicdata/getAreaList',
          payload: areaList,
        });
      }
      return response;
    },
    *fetchUpdate({ payload }, { call }) {
      const response = yield call(getUpdate, payload);
      return response;
    },
  },

  reducers: {
    getCorpList(state, { payload }) {
      return {
        ...state,
        uniCreditCode: payload[0].uniCreditCode,
        unitId: payload[0].companyName,
        corpId: payload[0].corpId,
        unitName: payload[0].companyName,
      };
    },
    updateComList(state, { payload }) {
      return {
        ...state,
        comList: payload,
        corpId: payload[0].corpId,
      };
    },
    getUserId(state, { payload }) {
      return {
        ...state,
        respDataList: payload,
      };
    },
    getInsLsPkg(state, { payload }) {
      return {
        ...state,
        supplyList: payload,
      };
    },
    getPlcyParam(state, { payload }) {
      const newState = state;
      if (payload && JSON.stringify(payload) !== '{}') {
        newState.insUnifyFlag = payload.insUnifyFlag || 3;
      }
      return {
        ...state,
      };
    },

    getDetailInfor(state, { payload }) {
      const newState = _.cloneDeep(state);
      Object.keys(payload).forEach(key => {
        if (key === 'insKindsList') {
          if (String(payload[key][0].insKindId) === '1' || Number(newState.sysCode) === 2) {
            newState.insUnifyFlag = '1';
            newState.isRequire = true;
            newState.insKindsArr = ['1'];
          } else {
            newState.insUnifyFlag = '2';
            // 判断是否有5
            newState.isRequire = payload.insKinds.indexOf('5') >= 0;
            newState.insKindsArr = payload.insKinds.split(',');
          }
        } else if (key === 'insPkgList') {
          const tempArr = [];
          payload.insPkgList.forEach(value => {
            if (newState.supplyList.some(item => item.insLsPkgId === value.insLsPkgId)) {
              tempArr.push(value.insLsPkgId);
            } else {
              newState.supplyListFlag = false;
              newState.insPkgList = payload.insPkgList;
              tempArr.push(value.insLsPkgName);
            }
          });
          newState.insLsPkgIdsList = tempArr;
        } else if (key === 'respList') {
          payload[key].forEach(item => {
            // 转换内容，能匹配到负责人push Id，不能的push Name
            if (newState.respDataList.some(pdItem => pdItem.userId === item.respId)) {
              newState.respListArr.push(item.respId);
            } else {
              newState.respListArr.push(item.respName);
            }
          });
        }
      });
      return {
        ...state,
        ...newState,
        ...payload,
        corpId: payload.unitId,
      };
    },
    addList(state) {
      const newData = state.injRatioList;
      let beginYm;
      let rangeDate;
      if (!newData || !newData.length) {
        beginYm = null;
        rangeDate = null;
      } else if (!newData[0].beginYm) {
        beginYm = moment(new Date()).format('YYYYMM');
        rangeDate = null;
      } else {
        rangeDate = moment(`${newData[0].beginYm}01`)
          .add(1, 'months')
          .format('YYYYMM');
        beginYm =
          moment(new Date()).format('YYYYMM') > rangeDate
            ? moment(new Date()).format('YYYYMM')
            : rangeDate;
      }
      newData.unshift({
        key: `list_${state.index}`,
        suppInsInjRatioId: null,
        beginYm,
        ratioVal: null,
      });

      // 确保table中的rowkey保持一致
      const newKeyData = newData.map(item => ({
        ...item,
        // key: item.key ? item.key : `list2_${state.index}`,
        key: item.key ? item.key : item.suppInsInjRatioId,
      }));

      return {
        ...state,
        rangeDate,
        injRatioList: newKeyData,
        index: state.index + 1,
      };
    },
    deleteList(state, { payload }) {
      const newData = state.injRatioList.filter(
        item => (item.suppInsInjRatioId || item.key) !== payload.key
      );
      return {
        ...state,
        injRatioList: newData,
      };
    },
    // 设置修改当前state数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
